package miggy.memory;

import miggy.api.config.MachineDefinition;
import miggy.api.config.ConfigurationException;
import miggy.api.cpu.Size;
import miggy.api.memory.CustomRegisterController;
import miggy.api.memory.CustomRegisterObserver;
import miggy.utils.TextUtil;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.logging.Logger;

/*
//  Miggy - Java Amiga MachineCore
//  Copyright (c) 2008, Tony Headford
//  All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
//  following conditions are met:
//
//    o  Redistributions of source code must retain the above copyright notice, this list of conditions and the
//       following disclaimer.
//    o  Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
//       following disclaimer in the documentation and/or other materials provided with the distribution.
//    o  Neither the name of the Miggy Project nor the names of its contributors may be used to endorse or promote
//       products derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
//  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
//  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
//  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
//  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// $Revision: 21 $
*/

public final class CustomRegisterManager implements CustomRegisterController
{
	private static Logger logger = Logger.getLogger("Miggy.CustomRegs");
	private final int size = 0x1000;
	private final ByteBuffer buffer;
	private ObserverList[] observers = new ObserverList[0x1000];
	private final int baseAddress;

	private int intena;
	private int intreq;
	private int dmacon;
	private int adkcon;

	public CustomRegisterManager()
	{
		logger.info("Creating CustomRegisterManager");

		baseAddress = CustomRegisters.CUSTOM_BASE;

		this.buffer = ByteBuffer.allocateDirect(size);

		intena = intreq = 0;

		for(int n = 0; n < 0x1000; n++)
		{
			observers[n] = null;
		}

		initObservers();
	}

	/**
	 * Initialise the controller
	 *
	 * @param config Configuration object containing machine settings
	 * @throws miggy.api.config.ConfigurationException
	 *          if Configuration holds invalid information for this component
	 */
	public void init(MachineDefinition config) throws ConfigurationException
	{
		
	}

	public int getBaseAddress()
	{
		return baseAddress;
	}

	public int getSize()
	{
		return 4;	//Single 4KB block
	}
	
	private void initObservers()
	{
		addObserver(CustomRegisters.INTENA, new CustomRegisterObserver() {
			public void update(int register, int value, Size size)
			{
				if((value & 0x8000) != 0)
				{
					intena |= value;
				}
				else
				{
					intena &= ~(value);
				}
			//	logger.info("INTENA: " + TextUtil.toHex((short)value) + " => " + TextUtil.toHex((short)intena));
				buffer.putShort(CustomRegisters.INTENAR - baseAddress, (short)(intena & 0x7fff));
			}
		});

		addObserver(CustomRegisters.INTREQ, new CustomRegisterObserver() {
			public void update(int register, int value, Size size)
			{
				if((value & 0x8000) != 0)
				{
					intreq |= value;
				}
				else
				{
					intreq &= ~(value);
				}
			//	logger.info("INTREQ: " + TextUtil.toHex((short)value) + " => " + TextUtil.toHex((short)intreq));
				buffer.putShort(CustomRegisters.INTREQR - baseAddress, (short)(intreq & 0x7fff));
			}
		});

		addObserver(CustomRegisters.DMACON, new CustomRegisterObserver() {
			public void update(int register, int value, Size size)
			{
				if((value & 0x8000) != 0)
				{
					//or into existing value
					dmacon |= value;
				}
				else
				{
					//remove set values
					dmacon &= ~(value);
				}
				logger.info("DMACON: " + TextUtil.toHex((short)value) + " => " + TextUtil.toHex((short)dmacon));
				buffer.putShort(CustomRegisters.DMACONR - baseAddress, (short)(dmacon & 0x7fff));
			}}
		);

		addObserver(CustomRegisters.ADKCON, new CustomRegisterObserver() {
			public void update(int register, int value, Size size)
			{
				if((value & 0x8000) != 0)
				{
					//or into existing value
					adkcon |= value;
				}
				else
				{
					//remove set values
					adkcon &= ~(value);
				}
				logger.info("ADKCON: " + TextUtil.toHex((short)value) + " => " + TextUtil.toHex((short)adkcon));
				buffer.putShort(CustomRegisters.ADKCONR - baseAddress, (short)(adkcon & 0x7fff));
			}}
		);
	}

	public final void reset()
	{
		logger.info("Resetting CustomRegisterManager");
		intena = intreq = 0;
	}

	public final int peek(int address, Size size)
	{
		return read(address, size);
	}

	public final void poke(int address, int value, Size size)
	{
		write(address, value, size);

		//notify and observers that the value has changed
		ObserverList ol = observers[address - baseAddress];
		if(ol != null)
		{
			int s = ol.size();
			for(int n = 0; n < s; n++)
			{
				ol.get(n).update(address, value, size);
			}
		}
	}

	public final int directPeek(int address, Size size)
	{
		// view the stored copy
		return read(address, size);
	}

	public final void directPoke(int address, int value, Size size)
	{
		//do not trigger observers (?) so no side affects
		write(address, value, size);
	}

	private int read(int reg, Size size)
	{
		reg -= baseAddress;

		int val;
		switch(size)
		{
			case Byte:
			{
				val = buffer.get(reg);
				break;
			}
			case Word:
			{
				val = buffer.getShort(reg);
				break;
			}
			case Long:
			{
				val = buffer.getInt(reg);
				break;
			}
			default:
				throw new IllegalArgumentException("Invalid data size specified");
		}
		return val & size.mask();
	}

	private void write(int reg, int value, Size size)
	{
		reg -= baseAddress;

		switch(size)
		{
			case Byte:
			{
				buffer.put(reg, (byte)value);
				break;
			}
			case Word:
			{
				buffer.putShort(reg, (short)value);
				break;
			}
			case Long:
			{
				buffer.putInt(reg, value);
				break;
			}
			default:
				throw new IllegalArgumentException("Invalid data size specified");
		}
	}

	public void addObserver(int register, CustomRegisterObserver observer)
	{
		register -= baseAddress;
		ObserverList ol = observers[register];
		if(ol == null)
		{
			ol = new ObserverList();
			observers[register] = ol;
		}

		ol.add(observer);
	}

	public void removeObserver(int register, CustomRegisterObserver observer)
	{
		register -= baseAddress;
		ObserverList ol = observers[register];
		if(ol != null)
		{
			ol.remove(observer);
			if(ol.size() == 0)
			{
				observers[register] = null;
			}
		}
	}

	//to prevent warning/errors because of generic array creation
	private final class ObserverList extends ArrayList<CustomRegisterObserver> {}
}
